<?php 
/**
 * @version        $Id$
 * @author         master@xuewl.com
 * @copyright      Copyright (c) 2007 - 2014, Chongqing xuewl Information Technology Co., Ltd.
 * @link           http://www.xuewl.com
**/
namespace Member\Controller;
use \Admin\Controller\InitController;
if (!defined('MODULE_CACHE')) define('MODULE_CACHE', DATA_PATH.'caches_model/');
/**
 * 后台会员模型管理
 */
class MemberController extends InitController {
	public function _initialize() {
		parent::_initialize();
		$this->db = D('Member');
		$this->module_db = D('Module');
		$this->model_db = D('Model');
		$this->pagecurr = max(1, I('page', 0, 'intval'));
		$this->pagesize = 10;
		api('Cache/run', 'member_group');
	}

	/**
	 * 会员管理
	 * @author xuewl <master@xuewl.com>
	 */
	public function manage() {
		$sqlMap = array();		
		$grouplist = getcache('member_group', 'member');
		$modellists = getcache('model', 'commons');
		foreach ($grouplist as $k => $v) $grouplist[$k] = $v['name'];		
		$modellist = array();
		foreach ($modellists as $k => $v) {
			if($v['module'] != 'member' || $v['disabled'] == 1) continue;
			$modellist[$k] = $v['name'];
		}		
		if (submitcheck('search')) {
			$info = I('param.');
			$info['start_time'] = (!empty($info['start_time'])) ? strtotime($info['start_time']) : 0;
			$info['end_time'] = (!empty($info['end_time'])) ? strtotime($info['end_time']) : 0;
			/* 注册时间 */
			if ($info['start_time'] && $info['end_time']){
				$sqlMap['regdate'] = array("BETWEEN",array($info['start_time'],$info['end_time']));
			}else{
				if ($info['start_time'] > 0) {
				$sqlMap['regdate'] = array("EGT", $info['start_time']);
				}
				if ($info['end_time'] > 0) {
					$sqlMap['regdate'] = array("ELT", $info['end_time']);
				}
			}
			/* 当前状态 */
			$info['status'] = (int) $info['status'];
			if ($info['status'] > 0) {
				$sqlMap['islock'] = $info['status'];
			}
			/* 会员模型 */
			$info['modelid'] = (int) $info['modelid'];
			if ($info['modelid'] > 0) {
				$sqlMap['modelid'] = $info['modelid'];
			}
			/* 会员组 */
			$info['groupid'] = (int) $info['groupid'];
			if ($info['groupid'] > 0) {
				$sqlMap['groupid'] = $info['groupid'];
			}
			/* 关键字搜索类型 */
			$info['type'] = (int) $info['type'];
			if (trim($info['keyword'])) {
				switch ($info['type']) {
					case '1': //用户名
						$sqlMap['username'] = array("LIKE", "%".$info['keyword']."%");
						break;
					case '2': // 用户ID
						$sqlMap['userid'] = array("LIKE", "%".intval($info['keyword'])."%");
						break;
					case '3': // 注册邮箱
						$sqlMap['email'] = array("LIKE", "%".$info['keyword']."%");
						break;
					case '4': // 注册IP
						$sqlMap['regip'] = array("LIKE", "%".$info['keyword']."%");
						break;						
					default:
						$sqlMap['nickname'] = array("LIKE", "%".$info['keyword']."%");
						break;
				}
			}
		}
		$membercount = $this->db->where($sqlMap)->count();
		$memberlist = $this->db->where($sqlMap)->page($this->pagecurr, $this->pagesize)->select();
		$pages = page($membercount, $pagesize);
		/* 附加菜单 */
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\''.U('add').'\', title:\''.L('member_add').'\', width:\'700\', height:\'500\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('member_add'));
		$form =  new \Common\Library\form();
		include $this->admin_tpl('member_list');
	}

	/**
	 * 添加会员
	 * @author xuewl <master@xuewl.com>
	 */
	public function add() {
		//会员模型
		$models = getcache('model', 'commons');
		//会员组
		$groups = getcache('member_group','member');
		
		$modelid = I('modelid', '1', 'intval');
		$groupid = I('groupid', '1', 'intval');
		$setting = getcache('setting', 'member');
		if (IS_POST) {
			$info = I('post.');
			$MemberLogic = D('Member', 'Logic');
			$result = $MemberLogic->register($info);
			if (!$result) {
				$this->error($MemberLogic->getError());
			}
			$this->success('操作成功');
		} else {
			$form =  new \Common\Library\form();		
			$show_header = true;
			$show_validator = true;
			require MODULE_CACHE.'member_form.class.php';
			$member_form = new \member_form($modelid);
			$forminfos = $member_form->get();
			include $this->admin_tpl('member_add');
		}
	}
	/**
	 * 判断用户名是否存在
	 */
	public function public_checkname_ajax(){
		$username = isset($_GET['username']) && trim($_GET['username']) ? trim($_GET['username']) : exit(0);
		if(CHARSET != 'utf-8') {
			$username = iconv('utf-8', CHARSET, $username);
			$username = addslashes($username);
		}
		$status = $this->db->where(array('username'=>$username))->count();
		if($status > 0) {
			exit('0');
		} else {
			exit('1');
		}
	}
	/**
	 * 判断昵称是否存在
	 */
	public function public_checknickname_ajax(){
		$nickname = isset($_GET['nickname']) && trim($_GET['nickname']) ? trim($_GET['nickname']) : exit(0);
		if(CHARSET != 'utf-8') {
			$nickname = iconv('utf-8', CHARSET, $nickname);
			$nickname = addslashes($nickname);
		}
		$status = $this->db->where(array('nickname'=>$nickname))->count();
		if($status > 0){
			exit('0');
		}else{
			exit('1');
		}
	}
	/**
	 * 判断邮箱是否存在
	 */
	public function public_checkemail_ajax(){
		$email = isset($_GET['email']) && trim($_GET['email']) ? trim($_GET['email']) : exit(0);
		$status = $this->db->where(array('email'=>$email))->count();
		if($status > 0){
			exit('0');
		}else{
			exit('1');
		}
	}
	/**
	 * 编辑会员
	 * @author xuewl <masater@xuewl.com>
	 */
	public function edit($userid = 0) {
		$userid = (int) $userid;
		if($userid < 0 ){$this->error('参数错误');}
		$member_info = $this->db->where(array('userid'=>$userid))->find();
		$modelid = $this->db->getFieldByUserid($userid,'modelid');
		$groupid = $this->db->getFieldByUserid($userid,'groupid');
		//会员模型
		$models = getcache('model','commons');
		$tablename = $models[$modelid]['tablename'];
		$member_infos = M($tablename)->where(array('userid'=>$userid))->find();
		$memberinfo = array_merge($member_info,$member_infos);
		//会员组
		$member_group = getcache('member_group','member');
		//获取会员模型表单
		 require MODULE_CACHE.'member_form.class.php';
		 $member_form =  new \member_form($modelid);
		 $forminfos = $forminfos_arr = $member_form->get($memberinfo);
		 //万能字段过滤
		 foreach($forminfos as $field=>$info) {
		 	if($info['isomnipotent']) {
		 		unset($forminfos[$field]);
		 	} else {
		 		if($info['formtype']=='omnipotent') {
		 			foreach($forminfos_arr as $_fm=>$_fm_value) {
		 				if($_fm_value['isomnipotent']) {
		 					$info['form'] = str_replace('{'.$_fm.'}',$_fm_value['form'], $info['form']);
		 				}
		 			}
		 			$forminfos[$field]['form'] = $info['form'];
		 		}
		 	}
		 }
		 
		if (submitcheck('dosubmit')) {
			$info = I('post.');	
			$info_group = $info['info'];
			$info['password'] = md5(md5($info['password'].$member_info['encrypt']));
			if($tablename){
				$rs = M($tablename)->where(array('userid'=>$userid))->save($info_group);
			}
			$result = $this->db->where(array('userid'=>$userid))->save($info);
			if(!$result && $rs){
				$this->error($this->db->getError());
			}
			$this->success('操作成功');
		} else {
			$form =  new \Common\Library\form();
			$form_overdudate = $form::date('lastdate', date('Y-m-d H:i:s',$memberinfo['lastdate']), 1);
			include $this->admin_tpl('member_edit');
		}				
	}

	public function delete() {
		$models = getcache('model','commons');
		if (IS_POST && I('fromhash') == session('FROMHASH')) {
			$userid = (array) $_POST['userid'];
			if (!empty($userid)) {
				foreach ($userid as $uid) {
					$modelid = $this->db->getFieldByUserid($uid, 'modelid');
					if ($models[$modelid]['module'] == 'member') {
						$tablename = $models[$modelid]['tablename'];
						if ($tablename) {
							M($tablename)->where(array('userid' => $uid))->delete();
						}
					}
					$this->db->where(array('userid' => $uid))->delete();
				}
			}
			$this->success('操作成功');
		} else {
			$this->error('请勿非法访问');
		}
	}

	/**
	 * 会员锁定
	 * @author xuewl <master@xuewl.com>
	 */
	public function lock() {
		if (IS_POST && I('fromhash') == session('FROMHASH')) {
			$userid = (array) $_POST['userid'];
			if (!empty($userid)) {
				foreach ($userid as $uid) {
					$this->db->where(array('userid' => $uid))->setField('islock','1');
				}
			}
			$this->success('已将指定会员锁定');
		} else {
			$this->error('请勿非法访问');
		}				
	}

	/**
	 * 会员解锁
	 * @author xuewl <master@xuewl.com>
	 */
	public function unlock() {
		if (IS_POST && I('fromhash') == session('FROMHASH')) {
			$userid = (array) $_POST['userid'];
			if (!empty($userid)) {
				foreach ($userid as $uid) {
					$this->db->where(array('userid' => $uid))->setField('islock','0');
				}
			}
			$this->success('已将指定会员解锁');
		} else {
			$this->error('请勿非法访问');
		}			
	}

	/**
	 * 会员审核
	 * @author xuewl <master@xuewl.com>
	 */
	public function verify() {
		if (submitcheck('dosubmit')) {
			$params = I('request.');
			$uids = (array) $params['userid'];
			$type_var = array('pass' => '1', 'reject' => '-1', 'ignore' => '-2');
			$sqlMap = array();
			$sqlMap['userid'] = array("IN", $uids);
			if ($params['type'] != 'delete') {
				$status_val = $type_var[$params['type']];
				$this->db->where($sqlMap)->setField('status', $status_val);
				/* 发送邮件通知 */
				if ($params['sendemail'] && $params['message']) {
					foreach ($uids as $key => $uid) {
						$email = $this->db->getFieldByUserid($uid, 'email');
						helpers('mail');
						sendemail($email, '会员审核通知', $params['message']);
					}
				}
			} else {
				$this->db->where($sqlMap)->delete();
			}
			$this->success('操作成功');
		} else {
			$member_model = getcache('model', 'commons');
			$verify_status = array('-2' => '忽略', '-1' => '拒绝', '0' => '待审', '1' => '通过');
			$sqlMap = array();
			$sqlMap['status'] = array("NEQ", 1);
			$membercount = $this->db->where($sqlMap)->count();
			$memberlist = $this->db->where($sqlMap)->page($this->pagecurr, $this->pagesize)->select();
			$pages = page($membercount, $this->pagesize);
			include $this->admin_tpl('member_verify');
		}	
	}

	/**
	 * 查询会员资料
	 * @author xuewl <master@xuewl.com>
	 */
	public function memberinfo($userid = 0) {
		$userid = (int) $userid;
		if($userid < 0){$this->error('参数错误');}
		$member_info = $this->db->where(array('userid'=>$userid))->find();
		$member_info['groupname'] = D('MemberGroup')->getFieldByGroupid($member_info['groupid'],'name');
		$models = getcache('model','commons');
		$modelid = $this->db->getFieldByUserid($userid,'modelid');
		$modelname = $models[$modelid]['name'];
		$tablename = $models[$modelid]['tablename'];
		$member_infos = M($tablename)->where(array('userid'=>$userid))->find();
		$memberinfo = array_merge($member_info,$member_infos);
		//模型字段名称
		$model_fieldinfo = getcache('model_field_'.$modelid, 'model');
		$member_fieldinfo = array();
		//交换数组key值
		foreach($model_fieldinfo as $v) {
			if(!empty($memberinfo) && array_key_exists($v['field'], $memberinfo)) {
				$tmp = $memberinfo[$v['field']];
				unset($memberinfo[$v['field']]);
				$member_fieldinfo[$v['name']] = $tmp;
				unset($tmp);
			} else {
				$member_fieldinfo[$v['name']] = '';
			}
		}
		$show_header = true;
		include $this->admin_tpl('member_moreinfo');
	}

	public function setting() {
		$models = getcache('model', 'commons');
		foreach ($models as $k => $v) {
			if($v['module'] != 'member' || $v['disabled'] == 1) unset($models[$k]);
		}
		$_grouplist = getcache('member_group', 'member');
		$grouplist = array();
		foreach ($_grouplist as $k => $v) {
			if($k < 2) continue;
			$grouplist[$k] = $v['name'];
		}

		$member_setting = $this->module_db->getFieldByModule('Member', 'setting');
		$member_setting = unserialize($member_setting);
		if (submitcheck('dosubmit')) {
			$info = $_POST['info'];
			$result = $this->module_db->where(array('module' => 'Member'))->setField('setting', serialize($info));
			if (!$result) {
				$this->error('模块配置失败');
			}
			setcache('setting', $info, strtolower(MODULE_NAME));
			$this->success('操作成功');
		} else {
			$form = new \Common\Library\form();
			include $this->admin_tpl('member_setting');			
		}
	}
}